import { useEffect, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { X, ChevronRight, Search } from 'lucide-react';
import { Pagination } from '../components/Pagination';
import { setPageTitle } from '../lib/utils';
interface Article {
  id: string;
  title: string;
  category: string;
  image: string;
  excerpt: string;
  readTime: string;
  date: string;
  author: string;
  featured?: boolean;
  tags: string[];
}
export function Articles() {
  const [searchParams, setSearchParams] = useSearchParams();
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedCategory, setSelectedCategory] = useState<string>(searchParams.get('category') || '');
  const [selectedTag, setSelectedTag] = useState<string>(searchParams.get('tag') || '');
  const [searchQuery, setSearchQuery] = useState<string>(searchParams.get('q') || '');
  const [filteredArticles, setFilteredArticles] = useState<Article[]>([]);
  const articlesPerPage = 6;

  useEffect(() => {
    setPageTitle('Articles');
  }, []);
  // Mock articles data
  const articles: Article[] = [{
    id: 'article-001',
    title: "The Science of Double Cleansing: Why It's Essential",
    category: 'Skincare',
    image: 'https://images.unsplash.com/photo-1556228578-0d85b1a4d571?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: "Discover why beauty experts are advocating for this two-step cleansing method and how it can transform your skin's health and appearance.",
    readTime: '8 min read',
    date: 'June 15, 2023',
    author: 'Sofia Lindström',
    tags: ['cleansing', 'skincare routine', 'korean beauty']
  }, {
    id: 'article-002',
    title: '5 Morning Rituals to Boost Your Energy Naturally',
    category: 'Wellness',
    image: 'https://images.unsplash.com/photo-1515377905703-c4788e51af15?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: 'Start your day with these simple practices that increase energy levels, improve mood, and set a positive tone for the hours ahead.',
    readTime: '6 min read',
    date: 'June 10, 2023',
    author: 'Maya Johnson',
    tags: ['morning routine', 'energy', 'wellness tips']
  }, {
    id: 'article-003',
    title: 'Clean Makeup Brands That Actually Perform',
    category: 'Makeup',
    image: 'https://images.unsplash.com/photo-1522335789203-aabd1fc54bc9?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: "Our curated list of clean beauty brands that don't compromise on performance, pigmentation, or staying power.",
    readTime: '10 min read',
    date: 'June 5, 2023',
    author: 'Emma Chen',
    tags: ['clean beauty', 'makeup', 'product recommendations']
  }, {
    id: 'article-004',
    title: 'The Ultimate Evening Skincare Ritual',
    category: 'Skincare',
    image: 'https://images.unsplash.com/photo-1570172619644-dfd03ed5d881?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: 'Transform your nighttime routine into a luxurious ritual that promotes skin repair and creates a peaceful transition to sleep.',
    readTime: '7 min read',
    date: 'May 28, 2023',
    author: 'Sofia Lindström',
    tags: ['skincare routine', 'nighttime', 'self-care']
  }, {
    id: 'article-005',
    title: 'Facial Massage Techniques for Lymphatic Drainage',
    category: 'Wellness',
    image: 'https://images.unsplash.com/photo-1519823551278-64ac92734fb1?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: 'Learn how to reduce puffiness, boost circulation, and promote a natural glow with these simple facial massage techniques.',
    readTime: '9 min read',
    date: 'May 20, 2023',
    author: 'Maya Johnson',
    tags: ['facial massage', 'lymphatic drainage', 'gua sha']
  }, {
    id: 'article-006',
    title: 'How to Build a Minimalist Skincare Routine',
    category: 'Skincare',
    image: 'https://images.unsplash.com/photo-1556228720-195a672e8a03?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: 'Simplify your skincare without sacrificing results. Our guide to creating an effective routine with fewer products.',
    readTime: '5 min read',
    date: 'May 15, 2023',
    author: 'Emma Chen',
    tags: ['minimalism', 'skincare routine', 'essentials']
  }, {
    id: 'article-007',
    title: 'The Psychology of Scent: How Fragrance Affects Mood',
    category: 'Wellness',
    image: 'https://images.unsplash.com/photo-1616394584738-fc6e612e71b9?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: 'Explore the fascinating connection between scent and emotion, and how to use fragrance intentionally to enhance your wellbeing.',
    readTime: '11 min read',
    date: 'May 8, 2023',
    author: 'Maya Johnson',
    tags: ['aromatherapy', 'psychology', 'mood']
  }, {
    id: 'article-008',
    title: 'Summer Makeup Trends Worth Trying',
    category: 'Makeup',
    image: 'https://images.unsplash.com/photo-1631214540553-ff044a3ff1d4?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: 'From glowing skin to bold colors, these are the makeup trends that will dominate the season—and how to wear them.',
    readTime: '8 min read',
    date: 'May 1, 2023',
    author: 'Emma Chen',
    tags: ['trends', 'summer', 'makeup']
  }, {
    id: 'article-009',
    title: 'The Benefits of Cold Water Therapy',
    category: 'Wellness',
    image: 'https://images.unsplash.com/photo-1544367567-0f2fcb009e0b?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: 'Discover how incorporating cold water into your routine can boost immunity, improve skin, and enhance mental wellbeing.',
    readTime: '7 min read',
    date: 'April 25, 2023',
    author: 'Maya Johnson',
    featured: true,
    tags: ['cold therapy', 'immunity', 'skin health']
  }, {
    id: 'article-010',
    title: 'Ingredient Spotlight: Niacinamide',
    category: 'Skincare',
    image: 'https://images.unsplash.com/photo-1608248543803-ba4f8c70ae0b?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: 'Everything you need to know about this versatile skincare ingredient that seems to do it all—from reducing pores to evening skin tone.',
    readTime: '6 min read',
    date: 'April 18, 2023',
    author: 'Sofia Lindström',
    tags: ['ingredients', 'niacinamide', 'skin concerns']
  }, {
    id: 'article-011',
    title: 'How to Apply Concealer Like a Makeup Artist',
    category: 'Makeup',
    image: 'https://images.unsplash.com/photo-1631214542045-a78ea87ff29a?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: 'Professional tips and techniques to master concealer application for flawless coverage that looks natural, not cakey.',
    readTime: '9 min read',
    date: 'April 10, 2023',
    author: 'Emma Chen',
    tags: ['techniques', 'concealer', 'makeup tips']
  }, {
    id: 'article-012',
    title: 'The Art of Bathing: Creating a Spa Experience at Home',
    category: 'Wellness',
    image: 'https://images.unsplash.com/photo-1507652313519-d4e9174996dd?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    excerpt: 'Transform your bathroom into a sanctuary with these tips for creating a luxurious, therapeutic bathing ritual.',
    readTime: '8 min read',
    date: 'April 3, 2023',
    author: 'Maya Johnson',
    tags: ['bathing', 'relaxation', 'home spa']
  }];
  // Categories for filter
  const categories = [{
    id: '',
    name: 'All Categories'
  }, {
    id: 'Skincare',
    name: 'Skincare'
  }, {
    id: 'Makeup',
    name: 'Makeup'
  }, {
    id: 'Wellness',
    name: 'Wellness'
  }];
  const tags = [{
    id: '',
    name: 'All Tags'
  }];
  // Apply filters
  useEffect(() => {
    let filtered = [...articles];
    // Apply category filter
    if (selectedCategory) {
      filtered = filtered.filter(article => article.category === selectedCategory);
    }
    // Apply tag filter
    if (selectedTag) {
      filtered = filtered.filter(article => article.tags.includes(selectedTag));
    }
    // Apply search filter
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(article => article.title.toLowerCase().includes(query) || article.excerpt.toLowerCase().includes(query) || article.category.toLowerCase().includes(query) || article.tags.some(tag => tag.toLowerCase().includes(query)));
    }
    setFilteredArticles(filtered);
    setCurrentPage(1);
  }, [selectedCategory, selectedTag, searchQuery]);
  // Update URL params
  useEffect(() => {
    const params = new URLSearchParams();
    if (selectedCategory) params.set('category', selectedCategory);
    if (selectedTag) params.set('tag', selectedTag);
    if (searchQuery) params.set('q', searchQuery);
    setSearchParams(params);
  }, [selectedCategory, selectedTag, searchQuery, setSearchParams]);
  // Handle filter changes
  const handleCategoryChange = (category: string) => {
    setSelectedCategory(category);
  };
  const handleTagChange = (tag: string) => {
    setSelectedTag(tag);
  };
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
  };
  const clearFilters = () => {
    setSelectedCategory('');
    setSelectedTag('');
    setSearchQuery('');
  };
  // Calculate pagination
  const totalPages = Math.ceil(filteredArticles.length / articlesPerPage);
  const indexOfLastArticle = currentPage * articlesPerPage;
  const indexOfFirstArticle = indexOfLastArticle - articlesPerPage;
  const currentArticles = filteredArticles.slice(indexOfFirstArticle, indexOfLastArticle);
  const handlePageChange = (pageNumber: number) => {
    setCurrentPage(pageNumber);
    window.scrollTo(0, 0);
  };
  return <div className="max-w-7xl mx-auto px-4 md:px-8 lg:px-12 py-12">
      {/* Breadcrumbs */}
      <div className="flex items-center text-sm mb-8">
        <Link to="/" className="text-gray-500 hover:text-[#4a6b60]">
          Home
        </Link>
        <ChevronRight size={14} className="mx-2 text-gray-400" />
        <span className="text-[#4a4a4a]">Articles</span>
      </div>

      <div className="mb-10">
        <h1 className="font-serif text-3xl md:text-4xl text-[#4a4a4a] mb-4">
          Our Journal
        </h1>
        <p className="text-base max-w-3xl">
          Explore our collection of articles on skincare, makeup, and wellness.
          Discover tips, techniques, and insights to enhance your beauty ritual
          and overall wellbeing.
        </p>
      </div>

      {/* Search and Filter Bar */}
      <div className="bg-white p-6 rounded-lg shadow-sm mb-10">
        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex-1">
            <div className="relative">
              <input type="text" placeholder="Search articles..." value={searchQuery} onChange={handleSearchChange} className="w-full py-2 pl-10 pr-4 border border-[#e8e5e0] rounded-md focus:outline-none focus:border-[#4a6b60]" />
              <Search size={18} className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
            </div>
          </div>
          <div className="flex gap-4">
            <select value={selectedCategory} onChange={e => handleCategoryChange(e.target.value)} className="py-2 px-3 border border-[#e8e5e0] rounded-md focus:outline-none focus:border-[#4a6b60]">
              {categories.map(category => <option key={category.id} value={category.id}>
                  {category.name}
                </option>)}
            </select>
            <select value={selectedTag} onChange={e => handleTagChange(e.target.value)} className="py-2 px-3 border border-[#e8e5e0] rounded-md focus:outline-none focus:border-[#4a6b60]">
              {tags.map(tag => <option key={tag.id} value={tag.id}>
                  {tag.name}
                </option>)}
            </select>
          </div>
        </div>

        {/* Active filters */}
        {(selectedCategory || selectedTag || searchQuery) && <div className="mt-4 flex flex-wrap gap-2 items-center">
            <span className="text-sm font-medium">Active Filters:</span>
            {selectedCategory && <div className="flex items-center bg-[#f3f0eb] px-3 py-1 rounded-full text-sm">
                <span>Category: {selectedCategory}</span>
                <button onClick={() => handleCategoryChange('')} className="ml-2 text-[#4a4a4a]" aria-label={`Remove ${selectedCategory} filter`}>
                  <X size={14} />
                </button>
              </div>}
            {selectedTag && <div className="flex items-center bg-[#f3f0eb] px-3 py-1 rounded-full text-sm">
                <span>Tag: {selectedTag}</span>
                <button onClick={() => handleTagChange('')} className="ml-2 text-[#4a4a4a]" aria-label={`Remove ${selectedTag} filter`}>
                  <X size={14} />
                </button>
              </div>}
            {searchQuery && <div className="flex items-center bg-[#f3f0eb] px-3 py-1 rounded-full text-sm">
                <span>Search: "{searchQuery}"</span>
                <button onClick={() => setSearchQuery('')} className="ml-2 text-[#4a4a4a]" aria-label={`Remove search filter`}>
                  <X size={14} />
                </button>
              </div>}
            <button onClick={clearFilters} className="text-sm text-[#4a6b60] hover:underline">
              Clear All
            </button>
          </div>}
      </div>

      {/* Articles Grid */}
      {filteredArticles.length > 0 ? <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12">
            {currentArticles.map(article => <Link key={article.id} to={`/article/${article.id}`} className="bg-white rounded-lg overflow-hidden shadow-sm group hover:shadow-md transition-shadow">
                <div className="h-56 overflow-hidden">
                  <img src={article.image} alt={article.title} className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
                </div>
                <div className="p-6">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-xs uppercase tracking-wider text-[#4a6b60] font-medium">
                      {article.category}
                    </span>
                    <div className="flex items-center text-xs text-gray-500">
                      <span>{article.readTime}</span>
                    </div>
                  </div>
                  <h2 className="font-serif text-xl mb-3 group-hover:text-[#4a6b60] transition-colors">
                    {article.title}
                  </h2>
                  <p className="text-sm text-gray-600 mb-4 line-clamp-3">
                    {article.excerpt}
                  </p>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-gray-500">
                      {article.date}
                    </span>
                    <span className="text-sm font-medium">
                      By {article.author}
                    </span>
                  </div>
                </div>
              </Link>)}
          </div>

          {/* Pagination */}
          {filteredArticles.length > articlesPerPage && <Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={handlePageChange} />}
        </> : <div className="text-center py-16">
          <h2 className="font-serif text-2xl mb-4">No Articles Found</h2>
          <p className="text-gray-600 mb-8">
            We couldn't find any articles matching your search criteria.
          </p>
          <button onClick={clearFilters} className="bg-[#4a6b60] hover:bg-[#3d5a50] text-white px-6 py-3 rounded-md transition-colors">
            Clear Filters
          </button>
        </div>}
    </div>;
}